﻿package {

	import flash.utils.*;
	public class Base64 {

		private static const BASE64_CHARS:String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

		public static function Base64_encodeByteArray(data:ByteArray):String {
			// Initialise output
			var output:String = "";

			// Rewind ByteArray
			data.position = 0;
			var data_bytesAvailable:int = data.bytesAvailable;
			// while there are still bytes to be processed
			var cycle:int = data_bytesAvailable / 3;

			var dataPos:int;
			while (cycle) {

				output += BASE64_CHARS.charAt(data[dataPos] & 0xfc >> 2) + BASE64_CHARS.charAt(data[dataPos] & 0x03 << 4 | data[dataPos + 1] >> 4) + BASE64_CHARS.charAt(data[dataPos + 1] & 0x0f << 2 | data[dataPos + 2] >> 6) + BASE64_CHARS.charAt(data[dataPos + 2] & 0x3f);

				cycle--;
				dataPos+=3;
			}
			if (data_bytesAvailable%3==1) {
				output+=BASE64_CHARS.charAt(data[dataPos]&0xfc>>2)+BASE64_CHARS.charAt(data[dataPos]&0x03<<4)+"==";


			} else if (data_bytesAvailable%3==2) {
				output+=BASE64_CHARS.charAt(data[dataPos]&0xfc>>2)+BASE64_CHARS.charAt(data[dataPos]&0x03<<4|data[dataPos+1]>>4)+BASE64_CHARS.charAt(data[dataPos+1]&0x0f<<2)+"=";

			}


			// Return encoded data
			return output;
		}

		public static function Base64_decodeToByteArray(data:String):ByteArray {
			// Initialise output ByteArray for decoded data
			var output:ByteArray=new ByteArray  ;

			// Create data and output buffers
			//var dataBuffer_0 : int;
			var dataBuffer_1:int;
			var dataBuffer_2:int;
			var dataBuffer_3:int;

			// While there are data bytes left to be processed
			var stringLength:int=data.length;

			output.length=stringLength*3>>2;
			var outputPt:int;
			for (var i:int=0; i<stringLength; i+=4) {


				//dataBuffer_0 = BASE64_CHARS.indexOf(data.charAt(i ));
				dataBuffer_1=BASE64_CHARS.indexOf(data.charAt(i+1));
				dataBuffer_2=BASE64_CHARS.indexOf(data.charAt(i+2));
				dataBuffer_3=BASE64_CHARS.indexOf(data.charAt(i+3));


				output[outputPt++]=BASE64_CHARS.indexOf(data.charAt(i))<<2+dataBuffer_1&0x30>>4;
				output[outputPt++]=dataBuffer_1&0x0f<<4+dataBuffer_2&0x3c>>2;
				output[outputPt++]=dataBuffer_2&0x03<<6+dataBuffer_3;
			}


			if (dataBuffer_2==64) {
				output.length-=2;
			} else if (dataBuffer_3==64) {
				//trace ("here");
				output.length--;

			}

			output.position=0;
			// Return decoded data
			return output;
		}

	}
}